package com.iqiyi.pps.epg.web.thread;

import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.program.ProgramData;
import com.iqiyi.pps.epg.core.model.push.AutoPushMsg;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.program.ProgramService;
import com.iqiyi.pps.epg.core.service.push.AutoPushMsgService;
import com.iqiyi.pps.epg.core.utils.ApplicationContextUtil;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.MD5Util;
import com.iqiyi.pps.epg.web.service.cloudpush.HttpCloudPushService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.*;

/**
 * Created by zhang on 2016/2/2.
 */
public class AutoPushToDevicesThread implements Runnable {
    private static Logger logger = LoggerFactory.getLogger(AutoPushToDevicesThread.class);

    private static final String SECRET_KEY = "E137FD9A1C8452016B293B733CAA260F";

    private static final int PUSH_DEVICES_MSG_MAX = 5;

    private List<AutoPushMsg> autoPushMsgs;

    public AutoPushToDevicesThread(List<AutoPushMsg> autoPushMsgs) {
        this.autoPushMsgs = autoPushMsgs;
    }

    @Override
    public void run() {
        if (autoPushMsgs == null) {
            return;
        }
        ProgramService programService = (ProgramService) ApplicationContextUtil.getBean(ProgramService.class);
        ChannelService channelService = (ChannelService) ApplicationContextUtil.getBean(ChannelService.class);


        // 整理设备id号，满足20就push
        StringBuffer deviceids20 = new StringBuffer();
        StringBuffer ids = new StringBuffer();
        int pushDevicesCount = 0;

        String tempCombKey = null;
        long tempEpisodeId = 0;
        String tempAppId = null;
        Integer tempPlatformType = null;
        ProgramData programData = null;
        ChannelBase channelBase = null;

        for (Iterator<AutoPushMsg> iterator = autoPushMsgs.iterator(); iterator.hasNext(); ) {
            AutoPushMsg autoPushMsg = (AutoPushMsg) iterator.next();
            long id = autoPushMsg.getId();
            long episodeId = autoPushMsg.getEpisodeId();
            String deviceId = autoPushMsg.getDeviceId();
            int appId = autoPushMsg.getAppId();
            int platformType = autoPushMsg.getPlatformType();

            if (StringUtils.isEmpty(tempCombKey)) {
                tempEpisodeId = episodeId;
                tempAppId = appId + "";
                tempPlatformType = platformType;
                tempCombKey = new StringBuffer().append(episodeId).append(appId).append(platformType).toString();
            }
            String combKey = new StringBuffer().append(episodeId).append(appId).append(platformType).toString();
            boolean flag = combKey.equals(tempCombKey);
            // 根据 episodeId获取节目和频道信息
            if (programData == null) {
                programData = programService.findProgramDataById(episodeId);
                channelBase = channelService.getChannelBase(programData.getFatherId());
            }

            if (!iterator.hasNext()) {
                if (pushDevicesCount >= PUSH_DEVICES_MSG_MAX) {
                    // 推送两次组合数据，第一次
                    pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), tempAppId, tempPlatformType);
                    // 第二次
                    deviceids20 = new StringBuffer().append(deviceId).append(",");
                    ids = new StringBuffer().append(id).append(",");
                    pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), appId + "", platformType);
                } else {
                    if (!flag) {
                        // 推送两次组合数据，第一次
                        pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), tempAppId, tempPlatformType);
                        // 如果 episodeId变化则再获取一次
                        if (episodeId != tempEpisodeId) {
                            programData = programService.findProgramDataById(episodeId);
                            channelBase = channelService.getChannelBase(programData.getFatherId());
                            tempEpisodeId = episodeId;
                        }
                        // 第二次
                        deviceids20 = new StringBuffer().append(deviceId).append(",");
                        ids = new StringBuffer().append(id).append(",");
                        pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), appId + "", platformType);
                    } else {
                        deviceids20.append(deviceId).append(",");
                        ids.append(id).append(",");
                        pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), appId + "", platformType);
                    }
                }
            } else {
                if (pushDevicesCount >= PUSH_DEVICES_MSG_MAX || !flag) {
                    pushMsg(channelBase, programData, deviceids20.toString(), ids.toString(), tempAppId, tempPlatformType);

                    deviceids20 = new StringBuffer().append(deviceId).append(",");
                    ids = new StringBuffer().append(id).append(",");
                    pushDevicesCount = 1;
                    tempCombKey = combKey;
                    tempAppId = appId + "";
                    tempPlatformType = platformType;
                } else {
                    deviceids20.append(deviceId).append(",");
                    ids.append(id).append(",");
                    pushDevicesCount++;
                }
            }
            // 如果 episodeId变化则再获取一次
            if (episodeId != tempEpisodeId) {
                programData = programService.findProgramDataById(episodeId);
                channelBase = channelService.getChannelBase(programData.getFatherId());
                tempEpisodeId = episodeId;
            }
        }
    }

    private String getPushMsg(String episodeName, int type) {
        StringBuffer content = new StringBuffer();
        int length = episodeName.length();
        if (AutoPushMsg.AUTO_PUSH_TYPE_IOS == type) {
            content.append("您预约的直播：");
            if (length > 22) {
                content.append(episodeName.substring(0, 19)).append("...");
            } else {
                content.append(episodeName);
            }
            content.append("即将开始，点击观看>>");
        } else if (AutoPushMsg.AUTO_PUSH_TYPE_ANDRIOD == type) {
            if (length > 13) {
                content.append(episodeName.substring(0, 10)).append("...");
            } else {
                content.append(episodeName);
            }
            content.append("开始啦>>");
        }
        return content.toString();
    }

    private String getSign(Map<String, Object> params) {
        StringBuffer ksort = new StringBuffer();
        TreeMap<String, Object> treeMap = new TreeMap<>(params);
        for (Map.Entry<String, Object> entry : treeMap.entrySet()) {
            ksort.append(entry.getKey()).append("=").append(entry.getValue()).append("|");
        }
        ksort.append(SECRET_KEY);
        return MD5Util.getMD5String(ksort.toString());
    }

    private void pushMsg(ChannelBase channelBase, ProgramData programData, String deviceids20, String ids, String appId, Integer platformType) {
        AutoPushMsgService autoPushMsgService = (AutoPushMsgService) ApplicationContextUtil.getBean(AutoPushMsgService.class);
        Long pushTime = System.currentTimeMillis();
        int agentType = AutoPushMsg.AGENT_TYPE_EPG;
        int msgType = AutoPushMsg.MSG_TYPE_EPG;
        int duration = AutoPushMsg.DURATION;
        long channelQipuId = channelBase.getQipuId();
        long episodeQipuId = programData.getQipuId();
        String episodeName = programData.getPname();
        int bossStatus = programData.getFreeStatus();
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        String deviceIds = deviceids20.toString();
        if (deviceIds.endsWith(",")) {
            deviceIds = deviceIds.substring(0, deviceIds.length() - 1);
        }
        paramsMap.put("device_ids", deviceIds);
        paramsMap.put("app_id", appId);
        paramsMap.put("agenttype", agentType + "");
        paramsMap.put("platform_type", platformType);
        String msgId = "EPG" + pushTime + (int) (Math.random() * 10);
        paramsMap.put("msg_id", msgId);
        paramsMap.put("msg_type", msgType + "");
        paramsMap.put("duration", duration + "");
        String msgTitle = null;
        String msgContent = null;
        String msgAlertBody = null;
        if (AutoPushMsg.AUTO_PUSH_TYPE_ANDRIOD.equals(platformType)) {
            msgTitle = "您预约的直播节目开始啦";
            msgContent = getPushMsg(episodeName, AutoPushMsg.AUTO_PUSH_TYPE_ANDRIOD);
            paramsMap.put("msg_title", msgTitle);
            paramsMap.put("msg_content", msgContent);
        } else if (AutoPushMsg.AUTO_PUSH_TYPE_IOS.equals(platformType)) {
            msgAlertBody = getPushMsg(episodeName, AutoPushMsg.AUTO_PUSH_TYPE_IOS);
            paramsMap.put("msg_alert_body", msgAlertBody);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("channel_id", channelQipuId);
        jsonObject.put("episode_id", episodeQipuId);
        jsonObject.put("boss_status", bossStatus);
        String msgExt = jsonObject.toJSONString();
        paramsMap.put("msg_ext", msgExt);
        String sign = getSign(paramsMap);
        paramsMap.put("sign", sign);
        String pushResponse = null;
        int pushStatus = 0;
        try {
            JSONObject responseJson = HttpCloudPushService.pushToDevices(paramsMap);
            if (responseJson != null) {
                pushResponse = responseJson.toJSONString();
                String code = null;
                if (responseJson.containsKey("code")) {
                    code = responseJson.getString("code");
                }
                if (StringUtils.isNotEmpty(code) && Constants.CODE_SUC.equals(code)) {
                    pushStatus = AutoPushMsg.AUTO_PUSH_STATUS_SUCCESS;
                } else {
                    pushStatus = AutoPushMsg.AUTO_PUSH_STATUS_FAIL;
                }
            } else {
                pushStatus = AutoPushMsg.AUTO_PUSH_STATUS_FAIL;
            }
        } catch (Exception e) {
            logger.error("[AutoPushToDevicesThread][Http][pushDevices][Error]", e);
        }

        AutoPushMsg autoPushMsgModel = new AutoPushMsg();
        autoPushMsgModel.setAgentType(agentType);
        autoPushMsgModel.setMsgId(msgId);
        autoPushMsgModel.setMsgType(msgType);
        autoPushMsgModel.setDuration(duration);
        autoPushMsgModel.setMsgTitle(msgTitle);
        autoPushMsgModel.setMsgContent(msgContent);
        autoPushMsgModel.setMsgAlertBody(msgAlertBody);
        autoPushMsgModel.setMsgExt(msgExt);
        autoPushMsgModel.setSign(sign);
        autoPushMsgModel.setPushStatus(pushStatus);
        autoPushMsgModel.setPushResponse(pushResponse);
        autoPushMsgModel.setPushFinishTime(new Timestamp(System.currentTimeMillis()));
        autoPushMsgService.updatePushMsgById(ids.toString(), autoPushMsgModel);
    }
}
